package com.javaer666.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-09-06
 * Time: 11:04
 * To change this template use File | Settings | File Templates.
 */
public class MyAlgorithm2 implements StandardShardingAlgorithm<Long> {
    public static final String SHARING_COLUMNS_KEY = "sharding-columns";
    private Properties props;

    //保留配置的分片键。在当前算法中其实是没有用的。
    private Collection<String> shardingColumns;

    public Collection<String> getShardingColumns(final Properties props) {
        String property = props.getProperty(SHARING_COLUMNS_KEY, "");
        return property.isEmpty()? Collections.emptyList(): Arrays.asList(property.split(","));
    }

    //精确查询 =或者in可以拿到分片键的精确值 返回一个分片
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        return null;
    }

    //范围查询 返回集合
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        //select * from course where cid in() and user_id   between {lowerEndpoint} and {upperEndpoint};
        Range<Long> userIdRange = shardingValue.getValueRange();

        Long lowerEndpoint = userIdRange.lowerEndpoint();
        Long upperEndpoint = userIdRange.upperEndpoint();
        List<String> result = new ArrayList<>();
        for (long i = lowerEndpoint; i <=upperEndpoint ; i++) {
            String logicTableName = shardingValue.getLogicTableName();
            //逻辑表名是course1 要把1去掉 再跟下面算的数值 找到真实表
            logicTableName = logicTableName.substring(0,logicTableName.length()-1);
            long num = ((i+1)%4)/2+1;
            String s = logicTableName + "_" + num;
            //m0 course1
            //m1 course1 course2
            if (availableTargetNames.contains(s)){
                result.add(s);
            }
        }
        return result;
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public void init(Properties props) {
        this.props = props;
        this.shardingColumns = getShardingColumns(props);
    }
}
